package com.hmall.item.listener;

import com.hmall.item.constants.MqConstants;
import com.hmall.item.service.ItemEsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @project hmall
 * @description 监听商品更新(update、delete、add)，修改es索引
 * @author WTX
 * @date 2025/8/12 11:47:21
 * @version 1.0
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class ItemIndexListener {
    private final ItemEsService itemEsService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConstants.ITEM_INDEX_UPDATE_QUEUE, durable = "true"),
            exchange = @Exchange(value = MqConstants.ITEM_INDEX_EXCHANGE),
            key = MqConstants.ITEM_INDEX_UPDATE_KEY
    ))
    public void listen(Map<String, Object> message) {
        log.info("收到商品更新消息：{}", message);
        long itemId = ((Number) message.get("itemId")).longValue();
        String type = (String) message.get("type");
        switch (type) {
            case "update":
            case "add":
                itemEsService.addItem(itemId);
                break;
            case "delete":
                itemEsService.deleteItem(itemId);
        }
    }
}

